package homework.Day0324.约瑟夫环;

import java.util.NoSuchElementException;

public class ArrayQueue<E> implements CounterQueue<E> {

    private int front;
    private int rear;
    private Object[] date;

    public ArrayQueue(int size) {
        date = new Object[size];
    }


    @Override
    public boolean isEmpty() {
        return rear == front;
    }

    @Override
    public int size() {
        if (rear >= front){
            return rear - front;
        }else {
            return date.length - front + rear;
        }
    }

    @Override
    public void enqueue(E e) {
        if (isEmpty()){
            grow();
        }
        date[rear] = e;
        rear = (rear + 1) % date.length;

    }

    public boolean isFull() {
        return (rear + 1) % date.length == front;
    }


    @Override
    public E dequeue() {
        if (isEmpty()){
            throw new NoSuchElementException("队列为空");
        }
        E rlt = (E) date[front];
        front = (front + 1) % date.length;
        return rlt;
    }

    public E element(){
        if (isEmpty()){
            throw new NoSuchElementException("队列为空");
        }
        return (E)date[front];
    }

    public void grow(){
        Object[] old = date;
        date = new Object[date.length*2];
        int j = 0;
        for (int i = this.front; i != this.rear ; i = (i + 1) % old.length) {
            date[j++] = old[i];
        }
        this.front = 0;
        this.rear = j;
    }

    public void clear(){
        rear = 0;
        front = 0;
    }
}
